import Vue from 'vue';
import Router from 'vue-router';
import store from "@/store";
Vue.use(Router);

const router = new Router({
    routes: [
        {
            path:'/',
            name:'Home',
            component:()=>import("../views/Home"),
            children:[
                {
                    path:'/smt/smt-01',
                    component:()=>import('@/components/Smt')
                },
                {
                    path:'/smt/smt-02',
                    component:()=>import('@/components/Smt2')
                },
                {
                    path:'/manage/employees',
                    component:()=>import('@/components/employees/Employees')
                }
            ]
        },
        {
            path:'/login',
            name:'Login',
            component:()=>import("../views/login/Login")
        },
        {
            path:'/insert',
            name:'insert',
            component:()=>import("@/components/employees/Insert")
        },
        {
            path:'*',
            component:()=>import("../views/404")
        }
    ],
});

router.beforeEach((to,from,next)=>{
    let token = localStorage.getItem('login-token');

    //访问login并且有token跳转到主页面
    if(token && to.path.endsWith('/login')){
        next('/');
        return;
    }

    //访问不是login而且没有token跳转login
    if(!token && !to.path.endsWith('/login')){
        next('/login');
        return;
    }

    console.log(store.state.menuList.length);
    if(store.state.menuList.length == 0){
        let menuList= [
            {
                title:'SMT车间',
                icon:'el-icon-location',
                path:'/smt',
                children:[
                    {
                        title:'车间1',
                        path:'smt-01',
                    },
                    {
                        title:'车间2',
                        path:'smt-02',
                    },
                    {
                        title:'车间3',
                        path:'smt-03',
                    }
                ]
            },
            {
                title:'管理',
                icon:'el-icon-s-custom',
                path:'/manage',
                children:[
                    {
                        title:'员工',
                        path:'employees',
                    },
                    {
                        title:'部门',
                        path:'department',
                    }
                ]
            }
        ];
        store.commit('changeMenuData',menuList);
    }
    next();

})

export default router;